<template>
  <div class="register-container">
    <div class="register-content">
      <div class="register-card">
        <div class="register-header">
          <h1 class="register-title">学生注册</h1>
          <p class="register-subtitle">校园智慧竞赛平台</p>
        </div>
        
        <form class="register-form" @submit.prevent="handleRegister">
          <div class="form-group">
            <input 
              type="text" 
              v-model="registerForm.studentId" 
              placeholder="请输入学号"
              class="form-input"
              @blur="checkStudentId"
              required
            />
          </div>
          
          <div class="form-group">
            <input 
              type="password" 
              v-model="registerForm.password" 
              placeholder="请输入密码"
              class="form-input"
              required
            />
          </div>
          
          <div class="form-group">
            <input 
              type="password" 
              v-model="registerForm.confirmPassword" 
              placeholder="请确认密码"
              class="form-input"
              required
            />
          </div>
          
          <div class="form-group">
            <input 
              type="text" 
              v-model="registerForm.realName" 
              placeholder="请输入真实姓名"
              class="form-input"
              required
            />
          </div>
          
          <div class="form-group">
            <input 
              type="number" 
              v-model="registerForm.age" 
              placeholder="请输入年龄"
              class="form-input"
              min="16"
              max="30"
              required
            />
          </div>
          
          <div class="form-group">
            <input 
              type="email" 
              v-model="registerForm.email" 
              placeholder="请输入邮箱地址"
              class="form-input"
              @blur="checkEmail"
              required
            />
          </div>
          
          <div class="form-group">
            <input 
              type="text" 
              v-model="registerForm.college" 
              placeholder="请输入学院"
              class="form-input"
              required
            />
          </div>
          
          <div class="form-group">
            <label class="skills-label">技能特长（可多选）：</label>
            <div class="skills-container" v-if="skillsList.length > 0">
              <div 
                v-for="skill in skillsList" 
                :key="skill.id"
                class="skill-item"
                :class="{ active: selectedSkills.includes(skill.id) }"
                @click="toggleSkill(skill.id)"
              >
                {{ skill.skillName }}
              </div>
            </div>
            <div v-else class="loading-skills">加载技能列表中...</div>
          </div>
          
          <button type="submit" class="register-btn">注册</button>
        </form>
        
        <div class="register-footer">
          <button class="link-btn" @click="handleBack">返回登录</button>
        </div>
      </div>
    </div>
    
    <!-- 自定义弹窗 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ modalTitle }}</h3>
        </div>
        <div class="modal-body">
          <p>{{ modalText }}</p>
        </div>
        <div class="modal-footer">
          <button class="modal-btn" @click="closeModal">确定</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore } from '@/stores/token.js'
import { studentRegisterService, checkStudentIdService, checkEmailService, getSkillsListService } from '@/api/student.js'

const router = useRouter()
const tokenStore = useTokenStore()

// 表单数据
const registerForm = reactive({
  studentId: '',
  password: '',
  confirmPassword: '',
  realName: '',
  age: '',
  email: '',
  college: '',
  skillIds: []
})

// 技能相关数据
const skillsList = ref([])
const selectedSkills = ref([])

// 弹窗控制
const showModal = ref(false)
const modalTitle = ref('')
const modalText = ref('')
const isRegisterSuccess = ref(false)  // 标记是否是注册成功的弹窗

// 显示弹窗
const showCustomModal = (title, text, type = 'info') => {
  modalTitle.value = title
  modalText.value = text
  showModal.value = true
  isRegisterSuccess.value = (type === 'success')  // 标记是否是成功弹窗
}

// 页面加载时获取技能列表
onMounted(async () => {
  try {
    const response = await getSkillsListService()
    if (response.code === 200) {
      skillsList.value = response.data
    } else {
      console.warn('获取技能列表失败:', response.msg)
      // 如果是认证失败，不显示错误弹窗，只在控制台记录
      if (response.code !== 401) {
        showCustomModal('提示', '获取技能列表失败，请刷新页面重试')
      }
    }
  } catch (error) {
    console.error('获取技能列表失败:', error)
    // 如果是401认证错误，不显示弹窗
    if (error.response && error.response.status === 401) {
      console.log('注册页面获取技能列表需要认证，这是正常现象')
    } else {
      showCustomModal('提示', '获取技能列表失败，请刷新页面重试')
    }
  }
})

// 切换技能选择
const toggleSkill = (skillId) => {
  const index = selectedSkills.value.indexOf(skillId)
  if (index > -1) {
    selectedSkills.value.splice(index, 1)
  } else {
    selectedSkills.value.push(skillId)
  }
  registerForm.skillIds = selectedSkills.value
}

// 检查学号是否存在
const checkStudentId = async () => {
  if (!registerForm.studentId) {
    return
  }
  
  try {
    const response = await checkStudentIdService(registerForm.studentId)
    if (response.code === 200 && response.data === true) {
      showCustomModal('提示', '该学号已存在，请使用其他学号')
    }
  } catch (error) {
    console.error('检查学号失败:', error)
    // 静默处理401错误，不显示提示
    if (error.response && error.response.status === 401) {
      console.log('检查学号接口需要认证，跳过检查')
    }
  }
}

// 检查邮箱是否存在
const checkEmail = async () => {
  if (!registerForm.email) {
    return
  }
  
  // 先验证邮箱格式
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailReg.test(registerForm.email)) {
    return // 格式不正确时不检查重复
  }
  
  try {
    const response = await checkEmailService(registerForm.email)
    if (response.code === 200 && response.data === true) {
      showCustomModal('提示', '该邮箱已被注册，请使用其他邮箱')
    }
  } catch (error) {
    console.error('检查邮箱失败:', error)
    // 静默处理401错误，不显示提示
    if (error.response && error.response.status === 401) {
      console.log('检查邮箱接口需要认证，跳过检查')
    }
  }
}

// 表单验证
const validateForm = async () => {
  if (!registerForm.studentId) {
    showCustomModal('提示', '请输入学号')
    return false
  }
  
  if (!registerForm.password) {
    showCustomModal('提示', '请输入密码')
    return false
  }
  
  if (registerForm.password.length < 6) {
    showCustomModal('提示', '密码长度不能少于6位')
    return false
  }
  
  if (registerForm.password !== registerForm.confirmPassword) {
    showCustomModal('提示', '两次输入的密码不一致')
    return false
  }
  
  if (!registerForm.realName) {
    showCustomModal('提示', '请输入真实姓名')
    return false
  }
  
  if (!registerForm.age) {
    showCustomModal('提示', '请输入年龄')
    return false
  }
  
  if (registerForm.age < 16 || registerForm.age > 30) {
    showCustomModal('提示', '年龄应在16-30岁之间')
    return false
  }
  
  // 邮箱验证
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!registerForm.email) {
    showCustomModal('提示', '请输入邮箱地址')
    return false
  } else if (!emailReg.test(registerForm.email)) {
    showCustomModal('提示', '请输入正确的邮箱格式')
    return false
  }
  
  if (!registerForm.college) {
    showCustomModal('提示', '请输入学院')
    return false
  }
  
  if (selectedSkills.value.length === 0) {
    showCustomModal('提示', '请至少选择一项技能特长')
    return false
  }
  
  return true
}

// 注册处理
const handleRegister = async () => {
  if (!(await validateForm())) {
    return
  }
  
  try {
    // 调用注册API
    console.log('提交注册信息:', registerForm)
  
    const response = await studentRegisterService(registerForm)
    
    // 注册成功
    if (response.code === 200) {
      showCustomModal(
        '注册申请已提交', 
        '您的注册申请已成功提交！请等待管理员审核通过后再进行登录。审核通过前暂时无法登录系统。',
        'success'  // 标记为成功类型的弹窗
      )
    } else {
      showCustomModal('注册失败', response.message || '注册失败，请稍后重试')
    }
  } catch (error) {
    console.error('注册失败:', error)
    // 处理错误响应
    let errorMessage = error.msg || error.message || '注册过程中发生错误，请稍后重试'
    
    // 特殊错误处理
    if (errorMessage.includes('Duplicate entry') && errorMessage.includes('student_id')) {
      errorMessage = '该学号已存在，请使用其他学号'
    } else if (errorMessage.includes('Duplicate entry') && errorMessage.includes('email')) {
      errorMessage = '该邮箱已被注册，请使用其他邮箱'
    }
    
    showCustomModal('注册失败', errorMessage)
  }
}

// 返回登录
const handleBack = () => {
  router.push('/login')
}

// 重置表单
const resetForm = () => {
  // 重置表单数据
  registerForm.studentId = ''
  registerForm.password = ''
  registerForm.confirmPassword = ''
  registerForm.realName = ''
  registerForm.age = ''
  registerForm.email = ''
  registerForm.college = ''
  registerForm.skillIds = []
  
  // 重置选中的技能
  selectedSkills.value = []
  
  console.log('表单已重置')
}

// 关闭弹窗
const closeModal = () => {
  showModal.value = false
  
  // 如果是注册成功的弹窗，关闭后重置表单并跳转到登录页
  if (isRegisterSuccess.value) {
    resetForm()
    setTimeout(() => {
      router.push('/login')
    }, 300)  // 延迟一点时间让弹窗关闭动画完成
    isRegisterSuccess.value = false  // 重置标记
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #6278db 0%, #635da6 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  box-sizing: border-box;
}

.register-content {
  width: 100%;
  max-width: 450px;
  text-align: center;
}

.register-card {
  background: white;
  border-radius: 12px;
  padding: 40px 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
}

.register-header {
  margin-bottom: 30px;
}

.register-title {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px 0;
}

.register-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

.register-form {
  margin-bottom: 25px;
}

.form-group {
  margin-bottom: 20px;
  text-align: left;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e5e9;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #6278db;
}

.skills-label {
  display: block;
  margin-bottom: 10px;
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.skills-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.skill-item {
  padding: 6px 12px;
  background: #f5f5f5;
  border: 2px solid #e1e5e9;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  user-select: none;
}

.skill-item:hover {
  background: #e8f0fe;
  border-color: #6278db;
}

.skill-item.active {
  background: #6278db;
  color: white;
  border-color: #6278db;
}

.loading-skills {
  text-align: center;
  color: #666;
  font-size: 14px;
  padding: 20px;
}

.register-btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #6278db 0%, #635da6 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  transition: transform 0.2s;
}

.register-btn:hover {
  transform: translateY(-2px);
}

.register-footer {
  text-align: center;
}

.link-btn {
  background: none;
  border: none;
  color: #6278db;
  font-size: 14px;
  cursor: pointer;
  text-decoration: underline;
}

.link-btn:hover {
  color: #5a6fd8;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 12px;
  padding: 0;
  max-width: 400px;
  width: 90%;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.modal-header {
  padding: 20px 24px 0;
  text-align: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.modal-body {
  padding: 16px 24px;
  text-align: center;
}

.modal-body p {
  margin: 8px 0;
  color: #666;
  line-height: 1.5;
}

.modal-footer {
  padding: 0 24px 20px;
  text-align: center;
}

.modal-btn {
  padding: 8px 24px;
  background: #6278db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.modal-btn:hover {
  background: #5a6fd8;
}
</style>
